package dt

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type Teachers struct {
	DataTable
}

func (cs *Teachers) GetTableInfo(start, length int, args ...string) error {
	centerId := ""
	teacherName := ""
	argsLen := len(args)
	if argsLen > 1 {
		centerId = args[0]
		teacherName = args[1]
	} else if argsLen == 1 {
		centerId = args[0]
	}

	// 起始位置和当前页面信息
	cs.Start = start
	cs.Length = length

	// 记录总数
	count, err := queryTeachersCount(centerId, teacherName)
	if err != nil {
		beego.Debug(err)
		return err
	}
	cs.RecordsTotal = count
	cs.RecordsFiltered = count

	// 当前记录信息
	centers, _, err := queryTeachers(start, length, centerId, teacherName)
	if err != nil {
		beego.Debug(err)
		return err
	}
	cs.Data = centers

	return nil
}

func queryTeachersCount(centerId, teacherName string) (int, error) {
	var count int
	o := orm.NewOrm()
	o.Using("default")
	sqlStr := `select
	           count(distinct(teacher_id))
                  from
                  t_schedule
                  where 1=1 `
	if centerId != "" && centerId != "0" {
		sqlStr = fmt.Sprint(sqlStr, ` and  center_id =`, centerId)
	}
	if teacherName != "" {
		sqlStr = fmt.Sprint(sqlStr, ` and  teacher_name like "%`, teacherName, `%" `)
	}

	err := o.Raw(sqlStr).QueryRow(&count)
	return count, err
}

func queryTeachers(start, length int, centerId, teacherName string) ([]models.Teacher, int64, error) {
	var teachers []models.Teacher
	o := orm.NewOrm()
	o.Using("default")
	sqlStr := `select
                   distinct(teacher_id) as teacher_id,
                   teacher_name,
                   center_id,
                   center_name
                   from
                   t_schedule where 1=1
	           `
	if centerId != "" && centerId != "0" {
		sqlStr = fmt.Sprint(sqlStr, ` and  center_id =`, centerId)
	}
	if teacherName != "" {
		sqlStr = fmt.Sprint(sqlStr, ` and  teacher_name like "%`, teacherName, `%" `)
	}

	sqlStr = fmt.Sprint(sqlStr, ` order by center_id, teacher_id limit `, start, ",", length)
	num, err := o.Raw(sqlStr).QueryRows(&teachers)
	beego.Debug(teachers)
	return teachers, num, err
}
